import * as React from 'react'
import { Table, Input, Button, Space, Form, InputNumber, message, Popconfirm, Row, Divider, Col, Card } from 'antd';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import MyModal from '../notification-table/my-modal';


export interface UniversalComponentProps {
    name?: string;
    searchKeys?: string;
    supportExport?: boolean;
}

const UniversalComponent: React.FC<UniversalComponentProps> = function ({ name, searchKeys, supportExport, ...otherProps }) {

    const [searchTerm, setSearchTerm] = React.useState({});
    const [mainData, setMainData] = React.useState([{
        id: 1,
        code: '1',
        name: '1'
    }, {
        id: 2,
        code: '2',
        name: '2'
    }])
    const [subData, setSubData] = React.useState([])
    const [mainPostForm] = Form.useForm()
    const [mainUpdateForm] = Form.useForm()
    const [subPostForm] = Form.useForm()

    let searchKeyList = searchKeys.split(',').map(item => item.trim());
    //console.log(supportExport)

    //筛选功能
    const handleSearch = () => {
        //这里的查找是字符串包含 如果要完全匹配改成===
        let filteredData = mainData;

        for (var i in searchKeyList) {
            var searchKey = searchKeyList[i];
            if (searchKey === 'id')
                continue;
            if (searchTerm[searchKey]) {
                filteredData = filteredData.filter(item => item[searchKey].includes(searchTerm[searchKey]));
            }
        }
        //console.log(filteredData)
        setMainData(filteredData);
    }
    const resetSearch = () => {
        setSearchTerm({})
        //TODO: setMainData()
    }
    const SearchInput = () => {
        const handleInputChange = (key) => (e) => {
            setSearchTerm(prevState => ({
                ...prevState,
                [key]: e.target.value
            }));
            console.log(key, e.target.value);
        }
        return (
            <>
                <Space size='large'>
                    {searchKeyList.map(key => (
                        <Input
                            placeholder={"请输入" + key}
                            value={searchTerm[key]}
                            onChange={handleInputChange(key)}
                            style={{ width: 200 }}
                        />
                    ))}
                </Space>
            </>
        )
    }

    //主界面表格列
    let mainColumns = []
    let mainColumnsJson = {
        name: '名称',
        code: '编码',
        action: '操作'
    }
    for (var x in mainColumnsJson) {
        mainColumns.push({
            title: mainColumnsJson[x],
            dataIndex: x,
            key: x
        })
    }
    //自定义操作列渲染
    const targetObject = mainColumns.find(item => item.key === 'action');
    const edit = (record) => {
        mainUpdateForm.setFieldsValue(record);
        updateModalVisibility(1, true);
    }
    const deleteRow = (key) => {
        const newData = mainData.filter((item) => item.id !== key);
        setMainData(newData);
        //TODO Fetch DELETE
    };
    if (targetObject) {
        targetObject.render = (_, record) => {
            return (
                <>
                    <Space size='middle'>
                        <a href="#" onClick={() => edit(record)}><EditOutlined /> 编辑</a>
                        <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                            <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                        </Popconfirm>
                    </Space>
                </>
            )
        };
    }

    const codeObject = mainColumns.find(item => item.key === 'code');
    if(codeObject){
        codeObject.render = (_, record) => {
            return (
                <>
                    <a href="#" onClick={() => updateModalVisibility(0, true)}>{record.code}</a>
                </>
            )
        }
    }

    //console.log('mainColumns: ', mainColumns);

    //数据项子界面表格列
    let subColumns = []

    //对话框
    const [isModalVisible, setIsModalVisible] = React.useState([false, false, false]);

    // 修改第 i 个元素的值
    const updateModalVisibility = (i: number, newValue: boolean) => {
        setIsModalVisible(prevState => {
            // 创建一个新的数组，避免直接修改原数组
            const newArray = [...prevState];
            newArray[i] = newValue; // 修改第 i 个元素
            return newArray;
        });
    };
    const onFinish = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(0, false);
    };
    const submitMainUpdateForm = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(1, false);
    }

    const formItemsJson =
        [
            {
                gutter: 16,
                cols: [
                    {
                        span: 12,
                        label: '通知单编号',
                        name: 'code',
                        type: 'Input',
                        placeholder: '通知单编号'
                    },
                    {
                        span: 12,
                        label: '通知单名称',
                        name: 'name',
                        type: 'Input',
                        placeholder: '通知单名称'
                    }
                ]
            },
            {
                cols: [
                    {
                        span: 24,
                        label: '备注',
                        name: 'note',
                        type: 'TextArea',
                        placeholder: '请输入备注',
                        rows: 3
                    }
                ]
            }
        ]


    //Json生成表单
    const DynamicForm = ({ formItemsJson }) => {
        return (
            <>
                {formItemsJson.map((row, rowIndex) => (
                    <Row key={rowIndex} gutter={row.gutter || 0}>
                        {row.cols.map((col, colIndex) => (
                            <Col key={colIndex} span={col.span}>
                                <Form.Item label={col.label} name={col.name}>
                                    {col.type === 'Input' && <Input placeholder={col.placeholder} />}
                                    {col.type === 'TextArea' && <Input.TextArea placeholder={col.placeholder} rows={col.rows} />}
                                </Form.Item>
                            </Col>
                        ))}
                    </Row>
                ))}
            </>
        );
    };

    const CustomForm = () => {
        return (
            <>
                <Form form={mainPostForm} name='mainPostForm' onFinish={() => onFinish} layout="vertical" labelAlign='left'>
                    <DynamicForm formItemsJson={formItemsJson} />
                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(0, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" >提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )
    }

    const CustomFormWithTable = () => {
        return (
            <>
                <Form form={mainUpdateForm} name="mainUpdateForm" onFinish={() => submitMainUpdateForm} layout="vertical" labelAlign='left'>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="通知单编号" name="code">
                                <Input placeholder="通知单编号" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="通知单名称" name="name">
                                <Input placeholder="通知单名称" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="采购单编号" name="purchaseNumber">
                                <Input placeholder="采购单编号" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="供应商" name="vendorName">
                                <Input placeholder="供应商" />
                            </Form.Item>
                        </Col>



                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="到货日期" name="date">
                                <Input placeholder="到货日期" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="联系人" name="contact">
                                <Input placeholder="联系人" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="联系方式" name="phone">
                                <Input placeholder="联系方式" />
                            </Form.Item>
                        </Col>



                    </Row>
                    <Divider>物料信息</Divider>
                    <Card extra={<Button type="primary" onClick={() => updateModalVisibility(2, true)}>新增</Button>}>
                        <Table columns={subColumns} dataSource={subData}></Table>
                    </Card>


                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(1, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" >提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )
    }

    return (
        <div style={{ marginTop: 20, marginLeft: 20 }}>
            <Space size='large'>
                <SearchInput />
                <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                    搜索
                </Button>
                <Button icon={<ReloadOutlined />} onClick={resetSearch}>
                    重置
                </Button>
                <Button type="primary" onClick={() => updateModalVisibility(0, true)}>
                    + 新增
                </Button>
                {/* 主界面新增对话框 一个Form*/}
                <MyModal open={isModalVisible[0]} onCancel={() => updateModalVisibility(0, false)}>
                    <CustomForm />
                </MyModal>
                {/* 主界面更新对话框 包括一个Form和一个Table */}
                <MyModal open={isModalVisible[1]} onCancel={() => updateModalVisibility(1, false)}>
                    <CustomFormWithTable />
                </MyModal>
                {/* 子界面新增对话框 一个Form*/}
                <MyModal open={isModalVisible[2]} onCancel={() => updateModalVisibility(2, false)}>
                    <CustomForm />
                </MyModal>
            </Space>
            <Divider />
            <Row>
                <Table dataSource={mainData} columns={mainColumns} style={{ width: '100%' }}></Table>
            </Row>
        </div>
    )

}

UniversalComponent.displayName = '通用组件'
export default UniversalComponent;